from functools import reduce
import re
import sqlite3
import pymysql

# 2024.10.22
# list 列表： 相当于一个“超”数组

# 有序集合，可以随时添加和删除其中的元素

classmates = ['Mike', 'Bob', 'Tracy']
print(classmates)
print(classmates[1])
# print(classmates[3]) 越界了
print(classmates[-1])

# 直接加到最后
classmates.append('Jack')
print(classmates)
# 在到Bob后
classmates.insert(2, 'Rose')
print(classmates)
# 去除下标为2的
classmates.pop(2)
print(classmates)

# 引用 修改 数据类型可以不同 嵌套

# 使用tuple 元组
# 一旦初始化不能修改，适用于实验的参考系，（不想让改变的）
classmates = ('Mike', 'Bob', 'Tracy')

# list 可以为空
L = []
# tuple 可以为空
T = ()

# T = (1)
T = 1
# 按整数1打印
print(type(T))

T = (1,)
print(type(T))

# dict 也叫map,键-值（key-value）对组成

d = {'a': 10, 'b': 20, 'c': 30}
print(d['a'])

d = {'a': 10, 'b': 20}
d['c'] = 30
print(d)
# key不存在，dict报错

# 判断key是否存在

if 'c' in d:
    print('true')

print(d.get('d', 'nokey'))

# set 一组key的集合，但不储存value set中没有重复的key 集合就是没有value的key
s = set([1, 2, 3])
print(s)

s.add(4)
print(s)

s.remove(2)
print(s)

# 2024.10.25

# 条件判断
# input输入的都是string类型
# x = input()
# if int(x) > 5:
#   print('aaaa')

# 循环 for...in循环
names = ['Mike', 'Bob', 'Tracy']

for name in names:
#   print(name)
    print(name, end='')

s = 'abcdefg'
s1 = ''
for c in s:
    print(str.upper(c))
    s1 += str.upper(c)
print(s1)

s1 += str.upper(s[0])
for c in s[1:]:
    s1 += str.lower(c)
print(s1)

L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sum = 0
# for l in L:
for l in range(11):  # 0-10 11个数

# for l in range(1, 11): 1-10的和

    sum += l
print(sum)

sum = 0
i = 1
while i <= 10:
    sum += i
    i += 1
print(sum)

L = ['Bart', 'Lisa', 'Adam']
for n in L:
    print('Hello,', n, '!')
    # print('Hello,%s!' % n)
    # Hello,Bart!
    # Hello,Lisa!
    # Hello,Adam!

# 函数
a = abs
print(a(-5))

abs = 5
print(abs)


def my_abs(a):
    # if a < 0:
    #     return -a
    # else:
    #     return a
    result = 0
    if a < 0:
        result = -a
    else:
        result = a
    return result


print(my_abs(-5))

# from 模块名 import 函数名

# 默认参数
# 默认参数往右放，因为默认参数不经常变化

# def enroll(name, gender, age=6, city='Beijing'):


# 可变参数

# 以list和tuple为参数


def calc(numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum


print(calc([1, 2, 3, 4]))

# 可变参数写法


def calc(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum


print(calc(1, 2, 3, 4))

# 拆包 解包
# list和tuple作可变参数
L = [1, 2, 3, 4]
print(calc(*L))

# 关键字参数
# 拓展函数的功能


def person(name, age, **kw):
    print('name:', name, 'age:', age, 'other:', kw)
    print('name:', name)
    print('age:', age)
    for k, v in kw.items():
        print(k + ':', v)
    # print('other attributes:', kw)


person('Mike', 30)
person('Bob', 35, city='Beijing')
person('Adam', 35, gende='M', job='Engineer')


# 命名关键字参数
# 例如：只接收city和job作为关键字参数
def person(name, age, *, city, job):
    print('aaa')

# person('mike', 19, city='BJ', job='PM', gender='M')


person('mike', 19, city='BJ', job='PM')


# 案例练习
def f1(a, b, c = 0, *args, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'args=', args, 'kw =', kw)


def f2(a, b, c = 0, *, d, **kw):
    print('a =', a, 'b =', b, 'c =', c, 'd=', d, 'kw =', kw)


f1(1, 2)
f1(1, 2, 3)
f1(1, 2, 3, 'a', 'b')
f1(1, 2, 3, 'a', 'b', x = 99)
f2(1, 2, 3, d = 'aaa', ext = None)

args = (1, 2, 3, 4)
kw = {'d': 99, 'x': '#'}
f1(*args, **kw)


args = (1, 2, 3)
kw = {'d': 99, 'x': '#'}
f2(*args, **kw)


def product(x, *y):
    result = x
    for n in y:
        result *= n
    return result


print(product(1, 2, 3, 4))

# 递归函数


def fact(n):
    result = 0

    if n == 1 or n == 0:
        result = 1
    else:
        return n * fact(n - 1)
    return result


print(fact(15))


def move(n, a, b, c):
    if n == 1:
        print(a, '->', c)
    else:
        move(n -1, a, c, b)
        print(a, '->', c)
        move(n-1, b, a, c)


move(5, 'A', 'B', 'C')


# 2024.11.1 切片(Slice) 迭代 列表生成式 生成器 迭代器


# L = []
# n = 1
# while n <= 99:
#     L.append(n)
#     n += 2
# print(L)

s = 'abcde'
print(s[0])


# 冒号左：起始位置，右边：终止元素后一个元素 从0开始，5-1终止
L = [1,2,3,4,5,6,7,8,9,10]
print(L[0:5])
print(L[-2:-1])  # 倒数第二个开始 9
print(L[-2:])  # 倒数第二个开始 9 10
print(L[::-1])

print((0, 1, 2, 3, 4, 5)[:3])


def trim(s):
    if s == ' ':
        return s
    if s[0] != ' ' and s[-1] != ' ':
        return s
    if s[0] == ' ':
        return trim(s[1:])
    if s[-1] == ' ':
        return trim(s[:-1])


print(trim('   abc   ') + 'bbb')


# 迭代
d = {'a':1, 'b':2, 'c':3}
for k in d:
    print(n)
for v in d.values():
    print(v)
for k, v in d.items():
    print(k,v)


# 如何判断一个对象是否可迭代

from collections.abc import Iterable
print(isinstance('abc', Iterable))
print(isinstance([1, 2, 3, 4], Iterable))
print(isinstance((1,), Iterable))
print(isinstance(123, Iterable))


def findMinAndMax(L):
    if len(L) != 0:
        maxvalue = L[0]
        minvalue = L[0]
        for x in L:
            if x > maxvalue:
                maxvalue = x
            if x < minvalue:
                minvalue = x
        return minvalue, maxvalue
    return None, None


print(findMinAndMax(L=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))

L = []
for x in range(1, 11):
    L.append(x * x)
print(L)
# 列表生成式：把代码放在一行
print([x * x for x in range(1, 11)])


L = [x for x in range(1, 201)]
print(L)  # 全部生成
# 生成器
g = (x for x in range(1, 11))
print(next(g))
print(next(g))
for n in g:  # 只要有next，有for也得接着来
    print(n)
# print(next(g))
# print(next(g))  # 随用随拿
# print(g)

# def fib(max):
#     n, a, b = 0, 0, 1
#     while n < max:
#         print(b)
#         a, b = b, a + b
#         n = n + 1
#     return 'done'
# fib(6)

# def fib(max):
#     n, a, b = 0, 0, 1
#     while n < max:
#         print(b)
#         x = input('下一个')
#         a, b = b, a + b
#         n = n + 1
#     return 'done'
# fib(6)

# 生成器函数


def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        # print(b)
        yield b
        a, b = b, a + b
        n = n + 1
    return 'done'


g = fib(6)
print(next(g))
print('other tasks 1000 lines')
print(next(g))
print('other tasks 1000 lines')
print(next(g))
print('other tasks 1000 lines')
print(next(g))
print('other tasks 1000 lines')
print(next(g))
print('other tasks 1000 lines')
print(next(g))
print('other tasks 1000 lines')
# print(next(g))
# print('other tasks 1000 lines')
# print(next(g))
# print('other tasks 1000 lines')
# print(next(g))
# print('other tasks 1000 lines')
# print(next(g))
# print('other tasks 1000 lines')
# print(next(g)) 迭代完了

# 全体自然数迭代器输出


def fun():
    num = 0
    while True:
        yield num
        num += 1


f = fun()
print(next(f))
print(next(f))
print(next(f))


def ruige_number_generator():
    for num in range(1000, 10000):
        # 将数字的每一位分别提取出来
        thousands = num // 1000
        hundreds = (num // 100) % 10
        tens = (num // 10) % 10
        ones = num % 10
        # 计算每一位的四次方之和
        # if power(thousands, 4)
        if thousands**4 + hundreds**4 + tens**4 + ones**4 == num:
            # print(num)
            yield num


# 输出所有瑞哥数
for ruige_num in ruige_number_generator():
    print(ruige_num)

# 异常处理

# class tooFewAppples(Exception):
#     errohint = 'apple不能比people少'
#
# def division():
#     apple = int(input("number of apples:"))
#     people = int(input("number of people:"))
#     if apple < people:
#         raise tooFewAppples('apple比people少')
#     result = apple // people
#     remain = apple - result * people
#     if remain > 0:
#         print(apple, '个苹果，平均分给', people, '个人，每个人分', result, '个,剩下', remain, '个')
#     else:
#         print(apple, '个苹果，平均分给', people, '个人，每个人分', result, '个')
#
#
# try:
#     division() # 有异常的代码块
# # except ZeroDivisionError:  # 可以不写，但不能乱写，如：写e
# #
# #     # 找到后的异常处理
# #     print('人数不能为0')
# # except ValueError as ve:
# #     print(ve)
# except (ZeroDivisionError, ValueError) as v:  # 处理异常
#     print(v)
# except tooFewAppples as ve:
#     print(ve.errohint)  # 输出：apple不能比people少
#     # print(ve) 输出：apple比people少
# else:  # 处理完异常的情况
#     print('成功分了一次苹果')
# finally:  # 不管异常有没有处理完都会执行
#     print('总算分了一次苹果')
# print('另外的代码。。。')  # 异常处理后的软着陆


# raise，类似于Java的throw，自定义异常，自己写异常类

# 把函数作为参数（高阶函数），函数的函数  另一个参数为可迭代的数据集list，tumple
def fun(num):
    return num * num


print(list(map(fun, [1, 2, 3, 4])))  # map的第一个参数只有一个参数


# def f1(function, L):
#     LL = []
#     for n in L:
#         LL.append(function(n))
#     return LL


# print(f1(fun, [1, 2, 3, 4]))


# map（映射）/reduce（归约）
# 两个参数：Iterable map
def fun(x):
    return x * x


L = [1, 2, 3, 4, 5, 6, 7, 8, 9]  # 可迭代
# print(map(fun, L))  打印结果：<map object at 0x0000020C7B903520>
print(list(map(fun, L)))  # 用list实例化

list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))

m = map(fun, L)
print(next(m))
for n in m:
    print(n)  # 1， 4， 9，不是1，1，4，9

# 导包 from functools import reduce


def f(x, y):
    return x + y


result = reduce(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(result)  # 算完是个数，45


def fn(x, y):
    return x * 10 + y
def str2num(s):
    d = {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    return d[s]


map(str2num, '13579')
result = reduce(fn, map(str2num, '13579'))
print(result)


# # 封装
# def str2int(s):
#     # def fn(x, y):
#     #     return x * 10 + y
#     lambda x, y: x * 10 + y
#     # def str2num(s):
#         d = {'1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
#         # return d[s]
#     lambda s: d[s]
#     # return reduce(fn, map(str2num, s))
#     return reduce(lambda x, y: x * 10 + y, map(lambda s: d[s], s))

# # 使用
# print(str2int('12345'))

# L1 = ['mike', 'tOM', 'JERRY']
# def fun(s):
#     return str.upper(s[0]) + str.lower(s[1:])
# print(list(map(lambda s:str.upper(s[0]) + str.lower(s[1:])), ))

# def prod(L):
#
#     #  return reduce(lambda x, y: x * y, L)
#
#     def fun(x, y):
#         return x * y
#     return reduce(fun, L)
#
#
# print(prod([1, 2, 3, 4, 5]))

# # filter过滤器
# L = [1,2,3,4,5,6,7]
#
# def is_even(x):
#     return x % 2 == 0
#
# # print(filter(is_even, L))
# print(list(filter(is_even, L)))
#
# def is_odd(x):
#     return x % 2 == 1
# print(list(filter(is_odd, L)))


# 用filter筛素数


# def _odd_iter():
#     n = 1
#     while True:
#         n = n + 2
#         yield n
#
#
# #  定义筛选函数
# def _not_divisible(n):
#     return lambda x: x % n > 0  # 返回值是函数(x也是变量，此处当作参数)
# # def _not_division(x):
# #     return x % 3 > 0
# def _not_division(x, n):
#     return x % n > 0
# # filter(_not_division, [3,5,7,9,11]) # n没法赋值，filter只有一个参数
# filter(_not_division(n), [3,5,7,9,11])
#
#
# def _not_division(n):
#     def fun(x):
#         return x % n > 0
#     return fun
#
# # filter(fun, []3,5,7,...)
# filter(_not_division(n), [3,5,7,9,11])


# sorted
#
# print(sorted([1, 3, -5, 7, -9]))  # 可以直接输出
#
# print(sorted([1, 3, -5, 7, -9], key=abs))

# print(sorted([1, 3, -5, 7, -9], key=abs, reverse=True))


# from functools import reduce
#
# # CYRTrans 实现瑞哥变换
# def CYRTrans(T):
#     C = len(str(T))  # 崔字画数
#     Y = 5  # 永字画数
#     R = 13  # 瑞字画数
#     return T * C + R - T // Y
#
# # 主程序
# def main():
#     numbers = range(10, 100)  # 所有两位整数
#     transformed_numbers = map(CYRTrans, numbers)  # 使用 map 进行瑞哥变换
#     filtered_numbers = filter(lambda x: x % 5 == 0, transformed_numbers)  # 筛选是 5 的倍数的数
#     result_sum = reduce(lambda x, y: x + y, filtered_numbers)  # 使用 reduce 计算总和
#     print("V5瑞数:", result_sum)
#
# if __name__ == "__main__":
#     main()


# from functools import reduce
#
# # CYRTrans 实现瑞哥变换
# def CYRTrans(T):
#     C = len(str(T))  # 崔字画数
#     Y = 5  # 永字画数
#     R = 13  # 瑞字画数
#     return T * C + R - T // Y
#
# # 计算 V5瑞数
# def calculate_V5():
#     numbers = range(10, 100)  # 所有两位整数
#     transformed_numbers = map(CYRTrans, numbers)  # 使用 map 进行瑞哥变换
#     filtered_numbers = filter(lambda x: x % 5 == 0, transformed_numbers)  # 筛选是 5 的倍数的数
#     result_sum = reduce(lambda x, y: x + y, filtered_numbers)  # 使用 reduce 计算总和
#     return result_sum
#
# # 计算傲娇瑞数
# def calculate_arrogant瑞数(n):
#     if not (3 <= n <= 8):
#         raise ValueError("n 必须在 3 和 8 之间")
#     numbers = range(10, 100)  # 所有两位整数
#     transformed_numbers = map(CYRTrans, numbers)  # 使用 map 进行瑞哥变换
#     filtered_numbers = filter(lambda x: x % n == 0, transformed_numbers)  # 筛选是 n 的倍数的数
#     arrogant瑞数 = sorted(filtered_numbers, reverse=True)  # 从大到小排序
#     return arrogant瑞数
#
# # 主程序
# if __name__ == "__main__":
#     # 计算并输出 V5瑞数
#     V5瑞数 = calculate_V5()
#     print("V5瑞数:", V5瑞数)
#
#     # 计算并输出傲娇瑞数 (n=8 和 n=7)
#     for n in [8, 7]:
#         result = calculate_arrogant瑞数(n)
#         print(f"傲娇瑞数 (n={n}):", result)

def createCounter():
    c = 0
    def counter():
        nonlocal c
        c += 1
        return c
    return counter

f = createCounter()


# print(f()) 每次累加1，计数器
# print(f())
# print(f())
# print(f())
for n in range(10, 100):
    if n % 5 == 0:
        print(f())


class Student(object):
# bart = Student()
# bart.name = 'Bart' 属性
# print(bart.name)
# mike = Student()
# print(mike.name)
    def __init__(self, n, a):
        # self.name = n public
        # self.age = a
        self.__name = n  # 私有属性
        self.__age = a
        self.__score = s
    def set_score(self, s):
        if 0 <= s <= 100:
            self.__score = s
        else:
            print('不能改')

# bart = Student('Bart', 19)
# print(bart.__name, bart.__age)
# Traceback (most recent call last):
#   File "D:\Bit_code\python_study\proj1\main.py", line 730, in <module>
#     print(bart.__name, bart.__age)
# AttributeError: 'Student' object has no attribute '__name'

# 编译器把属性改成'_Student__name'


class A(object):
    count = 0

    def __init__(self):
        self.name = 'aaa'  # 对象属性


a = A()
a.name = 'aaa'
b = A()
print(a.name, b.name)


class Animal(object):
    def run(self):
        print('The Animal is running...')


class Dog(Animal):  # 继承 节省代码
    def run(self):
        print('The Dog is running...')


class Cat(Animal):
    def run(self):
        print('The Cat is running...')


d = Dog()
d.run()
c = Cat()
c.run()


# def lowercase(s):
#     return s.lower()


def runtwice(animal):   # 多态 扩展性，可维护性
    animal.run()
    animal.run()


runtwice(Animal())
runtwice(Dog())
runtwice(Cat())


# 正则表达式
# ^表示行首，$表示行尾


def match_mobile_number(phone_number):
    # 定义正则表达式
    pattern = r"(13[4-9]\d{8})|(15[01289]\d{8})$"

    # 使用正则表达式匹配
    if re.match(pattern, phone_number):
        return True
    else:
        return False


# 测试部分
test_numbers = [
    "13412345678",  # 符合 13 开头，第三位是 4-9
    "15012345678",  # 符合 15 开头，第三位是 0,1,2,8,9
    "13312345678",  # 不符合条件
    "15812345678",  # 符合 15 开头，第三位是 8
]

# 输出测试结果
for number in test_numbers:
    result = "匹配" if match_mobile_number(number) else "不匹配"
    print(f"号码: {number} -> {result}")


#数据库
conn = sqlite3.connect('students.db') # 连接数据库
cursor = conn.cursor() # 游标
# cursor.execute('create table user (id int(10) primary key, name varchar(20))')  #主键primary key
# cursor.execute('insert into user (id, name) values ("1", "铁蛋")')
# cursor.execute('insert into user (id, name) values ("2", "二狗")')
# cursor.execute('insert into user (id, name) values ("3", "三丰")')
# cursor.execute('insert into user (id, name) values ("4", "四蛋")')
# stuName = input("输入加入名字：")
# sql = "insert into user (id, name) values ('%s', '%s')" %(5,"小王") # 增加
# sql = "insert into user (id, name) values ('%s', '%s')" %(6,username)
# sql = 'select * from user where name = ?'  # 查询
# sql = 'insert into user (id, name) values(?,?)'
# cursor.execute(sql, (8,'小赵'))
# students = [(9,'小雷'), (10,'小马')]
# sql = 'update user set name=?where id=?' # 修改
# cursor.execute(sql,('小刘',4))
# sql = 'delete from user where id = ?'
# cursor.execute(sql, (3, )) #删除第三个
# sql = 'delete from user'
# cursor.execute(sql) # 删除所有
#
# print(cursor.fetchone())
# print(cursor.fetchone())
# print(cursor.fetchall())
# cursor.close()
# conn.commit()
# conn.close()


db = pymysql.connect(host = 'localhost',user = 'root',passwd = 'root',database = 'firstdb')
cursor = db.cursor()
cursor.execute('SELECT * FROM user')
data = cursor.fetchone()
print(data)
cursor.close()
db.commit()
db.close()


























